/*
 * @Description: mark
 * @Author: wangwangwang
 * @Date: 2020-11-19 20:26:32
 * @LastEditors  : yangxr
 * @LastEditTime : 2021-12-27 15:01:55
 */
import axios from "axios";
import { Message } from "element-ui";
import { getToken, getUserId } from "@/utils/auth";
import router from "@/router/index";

// 创建axios实例
let baseURL = process.env.VUE_APP_API_HOST;
if (process.env.NODE_ENV == "development") {
  baseURL = "/dev";
  // baseURL = 'http://10.31.5.65/'
  // baseURL = 'http://10.31.5.66/'
  // baseURL = 'http://10.31.6.130:8088/'
}
const service = axios.create({
  baseURL: baseURL,
  timeout: 16000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json";
    if (getToken()) {
      config.headers["access-token"] = getToken();
      config.headers["user-id"] = getUserId();
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const { status, data } = response;
    if (status !== 200) {
      Message("网络出错！！！");
      return;
    }
    if (data.code === 1011) {
      const urlList = window.localStorage.getItem("urlList");
      sessionStorage.clear();
      localStorage.clear();
      window.localStorage.setItem("urlList", urlList);
      Message({
        message: "登录状态失效，请重新登录！！！",
        type: "warning",
        duration: 1000,
        onClose() {
          router.push("/login");
        },
      });
    } else if (data.code !== 1001 && data.code !== 1032) {
      Message({
        showClose: true,
        message: data.codeMsg,
        type: "warning",
      });
      return data;
    } else if (data.code == 1032) {
      Message({
        showClose: true,
        message: data.codeMsg,
        type: "warning",
      });
      return data;
    } else {
      return data;
    }
  },
  (error) => {
    Message({
      showClose: true,
      message: "网络出错请联系管理员处理。",
      type: "warning",
    });
    return Promise.reject(error);
  }
);
export default service;
